package com.srwl.mytx;

import android.app.Activity;
import android.app.Application;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import androidx.core.app.NotificationCompat;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.alibaba.fastjson.JSONObject;
import com.google.android.material.snackbar.Snackbar;
import com.srwl.mytx.activity.AudioChatActivity;
import com.srwl.mytx.activity.AudioRingingActivity;
import com.srwl.mytx.activity.VideoChatActivity;
import com.srwl.mytx.converter.MyRequestBodyConverter;
import com.srwl.mytx.dao.DBManager;
import com.srwl.mytx.domain.AliOssService;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.Contact;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.greendao.ContactDao;
import com.srwl.mytx.im.IMSClientBootstrap;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.UserService;
import com.srwl.mytx.task.ICallback;
import com.srwl.mytx.task.StarHttpUtil;
import com.srwl.mytx.utils.IDUtils;
import com.srwl.mytx.utils.PreferenceManager;
import com.srwl.mytx.utils.Utils;
import com.starrtc.starrtcsdk.api.XHClient;
import com.starrtc.starrtcsdk.api.XHConstants;
import com.starrtc.starrtcsdk.api.XHCustomConfig;
import com.starrtc.starrtcsdk.apiInterface.IXHErrorCallback;
import com.starrtc.starrtcsdk.apiInterface.IXHLoginManagerListener;
import com.starrtc.starrtcsdk.apiInterface.IXHResultCallback;
import com.starrtc.starrtcsdk.apiInterface.IXHVoipManagerListener;
import com.starrtc.starrtcsdk.core.camera.StarCamera;
import com.starrtc.starrtcsdk.core.videosrc.XHVideoSourceCallback;
import com.starrtc.starrtcsdk.core.videosrc.XHVideoSourceManager;

import org.json.JSONException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

//import io.agora.AgoraAPI;
//import io.agora.NativeAgoraAPI;

public class Helper {
    protected static final String TAG = "Helper";
    private static final String LOGIN_URL = "https://api.starrtc.com/public/authKey";

    private String userID;
    private String token;
    private boolean loginSuccess = false;//登录成功标志
    private int loginStatus = Constant.LOGIN_STATUS_NOT_LOGIN;
    private int tryLoginCount;

    boolean isStartingCall;

    private Map<String, User> mapContactList;
    private List<Contact> contactList;


    private static Helper instance = null;

    public SettingModel settingModel = null;

    private List<String> locationTaskList = new ArrayList<>();
    private Context appContext;
    public LocalBroadcastManager broadcastManager;
    //服务端软件版本
    private Integer serviceVersion;
    //更新详情
    private String updateLog;
    //最新版app下载地址
    private String apkUrl;
    private String basePath;
    private String filePath;
    private BroadcastReceiver receiver;
    private static final int NOTIFY_ID = 8;
    private static final String CHANNEL_NAME = "音视频通话";
    private static final String CHANNEL_ID = "video_chat";
    private NotificationManager notificationManager;
    private boolean networkConnected;
    private Handler handler = new Handler(Looper.getMainLooper());

    private Helper() {
    }

    public synchronized static Helper getInstance() {
        if (instance == null) {
            instance = new Helper();
        }
        return instance;
    }


    public void init(Application context) {
        networkConnected = Utils.isNetworkConnected(context);
        settingModel = new SettingModel(context);
        appContext = context;
        broadcastManager = LocalBroadcastManager.getInstance(appContext);
        //   autoLogin();
        loginStatus = Constant.LOGIN_STATUS_LOGINING;
        tryLogin();
        initBroadCast();

    }

    public boolean isStartingCall() {
        return isStartingCall;
    }

    public void setStartingCall(boolean startingCall) {
        isStartingCall = startingCall;
    }


    /**
     * user has logged into another device
     */

    /**
     * if ever logged in
     *
     * @return
     */
    public boolean isLoggedIn() {

        return loginSuccess;
    }

    public int getLoginStatus() {
        return loginStatus;
    }

    /**
     * logout
     */
    public void logout() {
        //清空当前登录用户的资料
        reset();

        // IMClientManager.getInstance().logout();
        IMSClientBootstrap.getInstance().logout();
        XHClient.getInstance().getLoginManager().logout();
    }


    public SettingModel getModel() {
        return settingModel;
    }

    public Contact getContact(String targetUserId) {
        for (Contact contact : contactList) {
            if (TextUtils.equals(contact.gettId(), targetUserId)) {
                return contact;
            }
        }
        return null;
    }

    /**
     * save single contact
     */

    public User getContactUserInfo(String targetUserId) {
        if (mapContactList == null) {
            initContactMap();
        }
        User user = mapContactList.get(targetUserId);//在好友联系人中查询

        if (user == null) {
            user = queryUserInfoById(targetUserId);
        }

        return user;
    }


    /**
     * 查询 数据库，根据 uId 获取联系人
     *
     * @param targetUserId
     * @return
     */
    public User queryUserInfoById(String targetUserId) {

        return DBManager.getInstance().getDaoSession().getUserDao().load(targetUserId);

    }

    /**
     * 判断是否是我的 正常的 联系人
     * 双边联系人，互相都没有删除对方
     *
     * @param checkId
     * @return
     */
    public boolean isNormalContact(String checkId) {
        for (Contact contact : contactList) {
            User targetUser = contact.getTargetUser();
            if (targetUser == null) {
                Log.e(TAG, "isNormalContact: 联系人中没有用户信息" + contact.toString());
                continue;
            }
            if (contact.getType()==null) {
                contact.setType(Constant.CONTACT_TYPE_NORMAL);
            }
            if (targetUser.getuId().equals(checkId) &&  contact.getType()!=Constant.CONTACT_TYPE_TEMP  && contact.getStatus().equals(Constant.CONTACT_STATUS_MUTUAL)) {
                return true;
            }
        }
        return false;
    }

    /**
     * get contact list
     *
     * @return
     */
    public Map<String, User> getMapContactList() {
        if (mapContactList == null) {
            mapContactList = new HashMap<>();
            initContactMap();
        }
        return mapContactList;
    }

    public void initContactMap() {
        List<Contact> contactList = getContactList();
        if (mapContactList == null) {
            mapContactList = new HashMap<>();
        }
        for (Contact contact : contactList) {
            User user = contact.getTargetUser();
            if (user == null) {
                continue;
            }
            mapContactList.put(user.getuId(), contact.getTargetUser());
        }
    }


    public List<Contact> getContactList() {

        if (contactList == null) {
            contactList = new ArrayList<>();
            // contactList = userDao.getContactList();

            //以position 排序的写法，但是不能搜索的时候排序，无意义
            // contactList.addAll(DBManager.getInstance().getDaoSession().getContactDao().queryBuilder().orderAsc(ContactDao.Properties.Position).list());
        } else {
            contactList.clear();
        }
        contactList.addAll(DBManager.getInstance().getDaoSession().getContactDao().loadAll());
        return contactList;
    }

    public void refreshCache() {
        mapContactList = null;
        contactList = null;
        getMapContactList();
    }


    /**
     * 登出的时候重置用户信息
     */
    public synchronized void reset() {
        //登出时候 清空当前登录用户信息
        removeLoginUserInfo();
        DBManager.getInstance().closeDB();
    }

    public void removeLoginUserInfo() {
        UserProfileManager.getInstance().reset();
        userID = null;
        token = null;
        mapContactList = null;
        if (contactList != null) {
            contactList.clear();
            contactList = null;
        }

        locationTaskList.clear();
    }


    private void autoLogin() {
        User loginUserInfo = UserProfileManager.getInstance().getLoginUserInfo();
//        if (TextUtils.isEmpty(token)) {
//            Log.d(TAG, "没有token，游客第一次登录");
//            String tempUserId = IDUtils.genOrderItemId();
//            tempLogin(tempUserId, 1);
//        } else {
//        }
        //正常用户
        if (loginUserInfo.getType() == Constant.USER_TYPE_NORMAL) {
            Log.d(TAG, "正常用户登录");
            String token = loginUserInfo.getToken();
            if (TextUtils.isEmpty(token)) {
                Log.i(TAG, "autoLogin: 没有token,不尝试自动登录");
                return;
            }
            login(token);
        } else {
            //临时用户
            int tempLoginCount = PreferenceManager.getInstance().getTempLoginCount();
            if (tempLoginCount == 1) {
                String tempUserId = IDUtils.genOrderItemId();
                loginUserInfo.setuId(tempUserId);
            }
            Log.d(TAG, "游客第" + tempLoginCount + "次登录");
            tempLogin(loginUserInfo.getuId(), tempLoginCount);
        }

    }

    private void tempLogin(String tempUserId, int tempLoginCount) {
        if (!Helper.getInstance().isNetworkConnected()) {
            Toast.makeText(appContext, appContext.getString(R.string.network_anomalies), Toast.LENGTH_SHORT).show();
            return;
        }
        Map<String, Object> body = new HashMap<>();
        body.put("uId", tempUserId);
        body.put("count", tempLoginCount);
        RetrofitManager.getInstance()
                .createRequest(UserService.class)
                .tempLogin(body)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        CommonResult commonResult = response.body();
                        if (!response.isSuccessful() || commonResult == null) {
                            Log.e(TAG, "游客临时登录失败:" + response.message());
                            // UserProfileManager.getInstance().reset();
                            tryLogin();
                            return;
                        }

                        if (commonResult.isError()) {
                            Log.e(TAG, "游客临时登录失败:" + commonResult.getMsg());
                            tryLogin();
                            return;
                        }

                        Log.i(TAG, "游客临时登录完成");
                        //重置 联系人显示模式为非 分组模式
                        PreferenceManager.getInstance().setSettingContactGroup(false);
                        JSONObject data = (JSONObject) commonResult.getData();
                        User tempUser = new User();
                        tempUser.setuId(tempUserId);
                        tempUser.setUsername("游客" + tempUserId.substring(tempUserId.length() - 5));
                        tempUser.setType(Constant.USER_TYPE_TEMP);//标记为临时用户，即游客
                        String token = data.getString("token");
                        String avatar = data.getString("avatar");
                        tempUser.setToken(token);
                        tempUser.setAvatar(avatar);
                        UserProfileManager.getInstance().syncLoginUserInfo(tempUser);
                        Contact tempContact = data.getObject("contact", Contact.class);
                        ContactDao contactDao = DBManager.getInstance().getDaoSession().getContactDao();
                        contactDao.insertOrReplace(tempContact);
                        DBManager.getInstance().getDaoSession().getUserDao().insertOrReplaceInTx(tempContact.getUser());
                        loginSuccess = true;
                        broadcastManager.sendBroadcast(new Intent(Constant.ACTION_AUTO_LOGIN_SUCCESS));
                        //后端回传的视频和图片地址
                        if (data.containsKey("topic_video_pre")) {
                            AliOssService.TOPIC_VIDEO_PRE_URL = data.getString("topic_video_pre");
                        }
                        if (data.containsKey("topic_image_pre")) {
                            AliOssService.TOPIC_IMAGE_PRE_URL = data.getString("topic_image_pre");
                        }
                        if (data.containsKey("live_host")) {
                            MLOC.resetLiveHost(data.getString("live_host"));
                        }
                        imLogin(tempUserId);
                        loginStatus = Constant.LOGIN_STATUS_LOGIN_SUCCESS;
                        //临时用户登录计数 +1
                        PreferenceManager.getInstance().setTempLoginCount(tempLoginCount + 1);
                        //保存版本信息
                        if (data.containsKey("versionInfo")) {
                            setVersionInfo(data.getJSONObject("versionInfo"));
                        }
                        if (data.containsKey("serviceTime")) {
                            MyApplication.timeOffset = data.getLong("serviceTime") - System.currentTimeMillis();
                        }
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        Log.e(TAG, "游客临时登录失败:" + t.getMessage());
                        //UserProfileManager.getInstance().reset();
                        tryLogin();

                    }
                });
    }

    private void imLogin(String tempUserId) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(3000); //延迟3s 登录，是为了大致在进入主页面的时候，才收到消息提示，如果有im 消息的话
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                IMSClientBootstrap.getInstance().login();
                initStarRtc(tempUserId);
                starRtcLogin();
            }
        }).start();
    }

    private void login(String currentUserToken) {
        if (!Helper.getInstance().isNetworkConnected()) {
            Toast.makeText(appContext, appContext.getString(R.string.network_anomalies), Toast.LENGTH_SHORT).show();
            return;
        }
        JSONObject body = new JSONObject();
        body.put("token", currentUserToken);
        RetrofitManager.getInstance()
                .createRequest(UserService.class)
                .autoLogin(body)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        CommonResult commonResult = response.body();
                        if (!response.isSuccessful() || commonResult == null) {
                            Log.e(TAG, "自动登录失败:" + response.message());
                            // UserProfileManager.getInstance().reset();
                            tryLogin();
                            return;
                        }

                        if (commonResult.isError()) {
                            //UserProfileManager.getInstance().reset();
                            tryLogin();
                            return;
                        }

                        Log.i(TAG, "自动登录完成");
                        JSONObject data = (JSONObject) commonResult.getData();
                        final User user = data.getObject("userInfo", User.class);
                        UserProfileManager.getInstance().syncLoginUserInfo(user);
                        broadcastManager.sendBroadcast(new Intent(Constant.ACTION_AUTO_LOGIN_SUCCESS));
                        //后端回传的视频和图片地址
                        if (data.containsKey("topic_video_pre")) {
                            AliOssService.TOPIC_VIDEO_PRE_URL = data.getString("topic_video_pre");
                        }
                        if (data.containsKey("topic_image_pre")) {
                            AliOssService.TOPIC_IMAGE_PRE_URL = data.getString("topic_image_pre");
                        }
                        if (data.containsKey("live_host")) {
                            MLOC.resetLiveHost(data.getString("live_host"));
                        }
                        imLogin(user.getuId());
                        loginSuccess = true;
                        loginStatus = Constant.LOGIN_STATUS_LOGIN_SUCCESS;
                        //保存版本信息
                        if (data.containsKey("versionInfo")) {
                            setVersionInfo(data.getJSONObject("versionInfo"));
                        }
                        if (data.containsKey("serviceTime")) {
                            MyApplication.timeOffset = data.getLong("serviceTime") - System.currentTimeMillis();
                        }

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        Log.e(TAG, "自动登录失败:" + t.getMessage());
                        tryLogin();
                    }
                });
    }


    /**
     * 尝试登录 记录次数 超过次数 不再尝试登录
     */
    private void tryLogin() {

        if (tryLoginCount < 3) {
            tryLoginCount++;
            Log.i(TAG, "tryLogin: 第 " + tryLoginCount + "次登录");
            autoLogin();
        } else {
            //超过3次尝试登录，均未成功，不再尝试，以登录失败 处理
            loginStatus = Constant.LOGIN_STATUS_LOGIN_FAIL;
        }
    }

    private void initBroadCast() {
        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {

                switch (intent.getAction()) {
                    case ConnectivityManager.CONNECTIVITY_ACTION:
                        networkConnected = Utils.isNetworkConnected(context);
                        if (networkConnected) {
                            if (loginStatus == Constant.LOGIN_STATUS_LOGIN_FAIL) {
                                //重置登录计数
                                tryLoginCount = 0;
                                Log.i(TAG, "onReceive: 网络恢复，登录状态为登录失败， 重试登录...");
                                loginStatus = Constant.LOGIN_STATUS_LOGINING;
                                tryLogin();
                            }
                        }

                        break;

                    case Intent.ACTION_TIME_TICK:
                        Log.i(TAG, "onReceive: 时间变化");
                        // getServiceTime(); 魅族16th 修改时间后，有时候没有回调，，原因未知，可能是系统版本问题，


                }
            }
        };
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        //  intentFilter.addAction(Intent.ACTION_TIME_TICK); //没分种回调一次，无用
        appContext.registerReceiver(receiver, intentFilter);
    }


    public void getVersionInfo() {
        RetrofitManager.getInstance().createRequest(UserService.class)
                .getVersion()
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "获取版本失败：" + response.message());
                            return;
                        }

                        if (result.isError()) {
                            Log.e(TAG, "获取版本失败：" + result.getMsg());
                            return;
                        }
                        JSONObject versionInfo = (JSONObject) result.getData();
                        Log.d(TAG, "获取版本信息完成：" + versionInfo);
                        setVersionInfo(versionInfo);
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        Log.e(TAG, "获取版本失败：" + t.getMessage());

                    }
                });

    }


    /**
     * 同步用户数据
     */
    public void syncUserInfo() {
        if (!Helper.getInstance().isNetworkConnected()) {
            Toast.makeText(appContext, appContext.getString(R.string.network_anomalies), Toast.LENGTH_SHORT).show();
            return;
        }
        JSONObject body = new JSONObject();
        body.put("token", UserProfileManager.getInstance().getLoginUserInfo().getToken());
        RetrofitManager.getInstance()
                .createRequest(UserService.class)
                .syncUserInfo(body)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        CommonResult commonResult = response.body();
                        if (!response.isSuccessful() || commonResult == null) {
                            Log.e(TAG, "同步用户信息失败:" + response.message());
                            return;
                        }

                        if (commonResult.isOK()) {
                            Log.i(TAG, "同步用户信息完成");
                            JSONObject data = (JSONObject) commonResult.getData();
                            final User user = data.getObject("userInfo", User.class);
                            //保存登录用户个人信息
                            UserProfileManager.getInstance().syncLoginUserInfo(user);
                            broadcastManager.sendBroadcast(new Intent(Constant.ACTION_USER_INFO_CHANGE));
                            //  List<Contact> contacts = JSONObject.parseArray(data.getString("contacts"), Contact.class);

                        }
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        Log.e(TAG, "同步用户信息失败:" + t.getMessage());
                    }
                });

    }

    public void setVersionInfo(JSONObject versionInfo) {
        if (versionInfo == null || versionInfo.size() == 0) {
            return;
        }
        if (versionInfo.getBigInteger("version") == null || versionInfo.getString("apk_url") == null || versionInfo.getString("updateLog") == null) {
            return;
        }
        Log.d(TAG, "获取版本信息完成：" + versionInfo);
        serviceVersion = versionInfo.getInteger("version");
        updateLog = versionInfo.getString("updateLog");
        apkUrl = versionInfo.getString("apk_url");
        updateLog = updateLog.replace("|", "\n");
    }

    /**
     * 检查更新
     */
    public void checkUpdate(Context context) {
        if (serviceVersion != null && updateLog != null && apkUrl != null) {
            UpdateManager manager = new UpdateManager(serviceVersion, apkUrl, updateLog, context);
            manager.checkUpdate();
        }
    }

    public void initStarRtc(String userID) {
        //初始化 完整版
        XHCustomConfig customConfig = XHCustomConfig.getInstance(appContext);
        customConfig.setAppId(MLOC.appId);

        customConfig.setChatroomServerUrl(MLOC.CHATROOM_SERVER_URL);
        customConfig.setLiveSrcServerUrl(MLOC.LIVE_SRC_SERVER_URL);
        customConfig.setLiveVdnServerUrl(MLOC.LIVE_VDN_SERVER_URL);
        customConfig.setImServerUrl(MLOC.IM_SERVER_URL);
        customConfig.setVoipServerUrl(MLOC.VOIP_SERVER_URL);
        customConfig.setDefConfigOpenGLESEnable(false);
        customConfig.setDefConfigCamera2Enable(false);
        StarCamera.setFrameBufferEnable(false);
        customConfig.initSDKForFree(userID, new IXHErrorCallback() {
            @Override
            public void error(final String errMsg, Object data) {
                Log.e(TAG, errMsg);
            }
        }, handler);
//设置输出视频的分辨率；
        // customConfig.setDefConfigVideoSize(XHConstants.XHCropTypeEnum.STAR_VIDEO_CONFIG_360BW_640BH_180SW_320SH);
        initStarRtcListener();
    }

    /**
     * 登录之前根据用户Id 获取授权key
     *
     * @param userId
     */
    public void getStatRtcAuthKey(String userId) {
        //  https://api.starrtc.com/public/authKey?userid=843281&appid=stargWeHN8Y7
        String url = LOGIN_URL + "?userid=" + userId + "&appid=" + MLOC.appId;
        Log.i(TAG, "getStatRtcAuthKey: url: " + url);
        String params = "";
        org.json.JSONObject jsonObject = new org.json.JSONObject();
        try {
            jsonObject.put("starUid", userId);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        params = jsonObject.toString();

        StarHttpUtil httpPost = new StarHttpUtil(StarHttpUtil.REQUEST_METHOD_GET);
        httpPost.addListener(new ICallback() {
            @Override
            public void callback(boolean reqSuccess, String statusCode, String authKey) {
                if (reqSuccess) {
                    if (statusCode.equals("1")) {
                        MLOC.authKey = authKey;
                        starRtcLogin();
                        return;
                    }
                }
                Log.e(TAG, "callback: 星盒获取授权key 失败");
            }
        });
        Bundle bundle = new Bundle();
        bundle.putString(StarHttpUtil.URL, url);
        bundle.putString(StarHttpUtil.DATA, params);
        httpPost.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, bundle);
    }

    public void starRtcLogin() {

        //登录SDK 需要验证用户权限
        XHClient.getInstance().getLoginManager().loginFree(new IXHResultCallback() {
            @Override
            public void success(Object data) {

                Log.i(TAG, "success: starRtc登录成功");
            }

            @Override
            public void failed(final String errMsg) {
                Log.e(TAG, errMsg);
                // MLOC.showMsg(KeepLiveService.this,errMsg);
            }
        });

    }

    /**
     * 设置语音通话的各种回调
     */
    private void initStarRtcListener() {


        XHClient.getInstance().getVoipManager().addListener(new IXHVoipManagerListener() {
            @Override
            public void onCalling(String uId) {
                Log.i(TAG, "onCalling: 收到视频通话呼叫... " + uId);
                //如果是android10,并且在app 处于后台，那么久弹出一个通知，告诉用户，有视频通话
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && MyApplication.activityCount == 0) {
                    notificationManager = ((NotificationManager) appContext.getSystemService(Context.NOTIFICATION_SERVICE));
                    NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
                    notificationManager.createNotificationChannel(channel);
                    Intent intent = new Intent(appContext, VideoChatActivity.class);
                    intent.putExtra("userId", uId);
                    intent.putExtra(VideoChatActivity.ACTION, VideoChatActivity.RING);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    PendingIntent pendingIntent = PendingIntent.getActivities(appContext, 0, new Intent[]{intent}, PendingIntent.FLAG_CANCEL_CURRENT);
                    NotificationCompat.Builder builder = new NotificationCompat.Builder(appContext, CHANNEL_ID);
                    Notification notification = builder
                            .setContentTitle("通知")
                            .setContentText("收到视频通话请求")
                            .setSmallIcon(R.mipmap.ic_launcher_10)
                            .setLargeIcon(BitmapFactory.decodeResource(appContext.getResources(), R.mipmap.ic_launcher_10))
                            .setAutoCancel(true)
                            .setContentIntent(pendingIntent)
                            .build();
                    notificationManager.notify(TAG, NOTIFY_ID, notification);

                } else {
                    Intent intent = new Intent(appContext, VideoChatActivity.class);
                    intent.putExtra("userId", uId);
                    intent.putExtra(VideoChatActivity.ACTION, VideoChatActivity.RING);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                    isStartingCall = true;
                    appContext.startActivity(intent);
                }
            }

            @Override
            public void onAudioCalling(String uId) {
                Log.i(TAG, "onAudioCalling: 收到语音呼叫 " + uId);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                    notificationManager = ((NotificationManager) appContext.getSystemService(Context.NOTIFICATION_SERVICE));
                    NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
                    notificationManager.createNotificationChannel(channel);
                    Intent intent = new Intent(appContext, AudioRingingActivity.class);
                    intent.putExtra("userId", uId);
                    intent.putExtra(AudioChatActivity.ACTION, AudioChatActivity.RING);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    PendingIntent pendingIntent = PendingIntent.getActivities(appContext, 0, new Intent[]{intent}, PendingIntent.FLAG_CANCEL_CURRENT);
                    NotificationCompat.Builder builder = new NotificationCompat.Builder(appContext, CHANNEL_ID);
                    Notification notification = builder
                            .setContentTitle("通知")
                            .setContentText("收到视频通话请求")
                            .setSmallIcon(R.mipmap.ic_launcher_10)
                            .setAutoCancel(true)
                            .setContentIntent(pendingIntent)
                            .build();
                    notificationManager.notify(TAG, NOTIFY_ID, notification);
                } else {
                    Intent intent = new Intent(appContext, AudioRingingActivity.class);
                    intent.putExtra("userId", uId);
                    intent.putExtra(AudioChatActivity.ACTION, AudioChatActivity.RING);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                    isStartingCall = true;
                    appContext.startActivity(intent);
                }
            }

            @Override
            public void onCancled(String s) {
                Log.i(TAG, "onCancled: 主叫方取消  " + s);

                broadcastManager.sendBroadcast(new Intent(Constant.ACTION_ON_CALL_CANCEL));
            }

            @Override
            public void onRefused(String s) {
                Log.i(TAG, "onRefused: 通话请求被拒绝 " + s);
                broadcastManager.sendBroadcast(new Intent(Constant.ACTION_ON_CALL_BE_REFUSE));
            }

            @Override
            public void onBusy(String s) {
                Log.i(TAG, "onBusy: 对方正在通过中 " + s);
                broadcastManager.sendBroadcast(new Intent(Constant.ACTION_ON_CALL_BUSY));
            }

            @Override
            public void onMiss(String s) {
                Log.i(TAG, "onMiss: 又有人呼入 " + s);
            }

            @Override
            public void onConnected(String s) {
                Log.i(TAG, "onConnected: 对方已经接受，通话接通 " + s);

                broadcastManager.sendBroadcast(new Intent(Constant.ACTION_ON_AUDIO_CONNECT));
            }

            @Override
            public void onHangup(String s) {
                Log.i(TAG, "onHangup: 对方已经挂断 " + s);
                broadcastManager.sendBroadcast(new Intent(Constant.ACTION_ON_HANG_UP));
            }

            @Override
            public void onError(String s) {
                Log.e(TAG, "onError: " + s);
                if (TextUtils.equals(s, "40007")) {
                    Log.i(TAG, "onError: 对方链接断开");
                    return;
                }
                broadcastManager.sendBroadcast(new Intent(Constant.ACTION_ON_CALL_ERROR));
            }

            @Override
            public void onReceiveRealtimeData(byte[] bytes) {
                Log.i(TAG, "onReceiveRealtimeData: 收到实时数据");
            }

            @Override
            public void onTransStateChanged(int i) {
                Log.i(TAG, "onTransStateChanged: 数据传输模式切换" + i);
            }
        });

        XHClient.getInstance().getLoginManager().addListener(new IXHLoginManagerListener() {
            @Override
            public void onConnectionStateChanged(XHConstants.XHSDKConnectionState xhsdkConnectionState) {
                Log.d(TAG, "onConnectionStateChanged: 登录状态改变" + xhsdkConnectionState.name());
            }

            @Override
            public void onKickedByOtherDeviceLogin() {
                Log.i(TAG, "onKickedByOtherDeviceLogin: 账户在其他设备登录");
            }

            @Override
            public void onLogout() {
                Log.i(TAG, "onImLogout: 登出。。。");
            }
        });
        XHVideoSourceManager.getInstance().setVideoSourceCallback(new XHVideoSourceCallback());

//        NativeAgoraAPI.CallBack agoraCallBack = new AgoraAPI.CallBack() {
//            @Override
//            public void onError(String name, int ecode, String desc) {
//                Log.d(TAG, "声网错误回调：  " + name + ":" + ecode + ":" + desc);
//            }
//
//            @Override
//            public void onReconnecting(int nretry) {
//
//                Log.d(TAG, "onReconnecting: 声网重新连接中。。。");
//            }
//
//            @Override
//            public void onRestLoginSuccess(int uid, int fd) {
//                Log.d(TAG, "声网登录成功");
//                Intent intent = new Intent(Constant.ACTION_ON_LOGIN_SUCCESS);
//                broadcastManager.sendBroadcast(intent);
//            }
//
//            @Override
//            public void onImLogout(int ecode) {
//                Log.d(TAG, "onImLogout: 声网下线：" + ecode);
////                switch (ecode) {
////                    case IAgoraAPI.ECODE_LOGOUT_E_KICKED:
////                    case IAgoraAPI.ECODE_LOGIN_E_TOKEN_KICKED:
////                        //被踢，账户在其他地方登陆
////                        onConnectionConflict();
////                        break;
////
////                }
//
//            }
//
//            @Override
//            public void onLoginFailed(int ecode) {
//                Log.d(TAG, "声网登录失败：  " + ecode);
//            }
//
//            @Override
//            public void onReconnected(int fd) {
//                Log.d(TAG, "声网重新连接：  " + fd);
//            }
//
//            @Override
//            /**
//             *当收到呼叫邀请时触发此回调。
//             */
//            public void onInviteReceived(String channelID, String account, int uid, String extra) {
//                Log.d(TAG, "收到呼叫");
//                Intent intent = new Intent(Constant.ACTION_ON_INVITE_RECEIVED);
//                intent.putExtra("channelID", channelID).putExtra("account", account).putExtra("uid", uid).putExtra("extra", extra);
//                broadcastManager.sendBroadcast(intent);
//
//
//            }
//
//            @Override
//            /**
//             * 发起邀请，对方收到邀请后，发起方将收到此回调
//             */
//            public void onInviteReceivedByPeer(String channelID, String account, int uid) {
//                Intent intent = new Intent(Constant.ACTION_ON_INVITE_RECEIVED_BY_PEER);
//                intent.putExtra("channelID", channelID).putExtra("account", account).putExtra("uid", uid);
//                broadcastManager.sendBroadcast(intent);
//            }
//
//
//            @Override
//            public void onInviteAcceptedByPeer(String channelID, String account, int uid, String extra) {
//                Intent intent = new Intent(Constant.ACTION_ON_INVITE_ACCEPTED_BY_PEER);
//                intent.putExtra("channelID", channelID).putExtra("account", account).putExtra("uid", uid).putExtra("extra", extra);
//                broadcastManager.sendBroadcast(intent);
//            }
//
//            @Override
//            public void onInviteRefusedByPeer(String channelID, String account, int uid, String extra) {
//                Intent intent = new Intent(Constant.ACTION_ON_HANG_UP);
//                intent.putExtra("channelID", channelID).putExtra("account", account).putExtra("uid", uid).putExtra("extra", extra);
//                broadcastManager.sendBroadcast(intent);
//            }
//
//            @Override
//            public void onInviteFailed(String channelID, String account, int uid, int ecode, String extra) {
//                Intent intent = new Intent(Constant.ACTION_ON_CALL_ERROR);
//                intent.putExtra("channelID", channelID).putExtra("account", account).putExtra("uid", uid)
//                        .putExtra("extra", extra).putExtra("ecode", ecode);
//                broadcastManager.sendBroadcast(intent);
//            }
//
//            @Override
//            public void onInviteEndByPeer(String channelID, String account, int uid, String extra) {
//                Intent intent = new Intent(Constant.ACTION_ON_INVITE_END_BY_PEER);
//                intent.putExtra("channelID", channelID).putExtra("account", account).putExtra("uid", uid)
//                        .putExtra("extra", extra);
//                broadcastManager.sendBroadcast(intent);
//            }
//
//            @Override
//            public void onChannelJoined(String channelID) {
//                Log.d(TAG, "加入频道成功:" + channelID);
//                Intent intent = new Intent(Constant.ACTION_ON_CHANNEL_JOINED);
//                intent.putExtra("channelID", channelID);
//                broadcastManager.sendBroadcast(intent);
//            }
//
//            @Override
//            public void onChannelJoinFailed(String channelID, int ecode) {
//                Log.d(TAG, "加入频道失败   " + channelID);
//                Intent intent = new Intent(Constant.ACTION_ON_CHANNEL_JOIN_FAILED);
//                intent.putExtra("channelID", channelID).putExtra("ecode", ecode);
//                broadcastManager.sendBroadcast(intent);
//            }
//
//            @Override
//            public void onMessageChannelReceive(String channelID, String account, int uid, String msg) {
//                Log.d(TAG, "onMessageChannelReceive: 收到频道消息  " + channelID);
//                Intent intent = new Intent(Constant.ACTION_ON_LIVE_ROOM_ADVERTISEMENT_PRICE_CHANGE);
//                intent.putExtra("account", account).putExtra("msg", msg);
//                broadcastManager.sendBroadcast(intent);
//            }
//
//            @Override
//            public void onChannelUserJoined(String account, int uid) {
//                Intent intent = new Intent(Constant.ACTION_ON_CHANNEL_USER_JOINED);
//                intent.putExtra("account", account);
//                broadcastManager.sendBroadcast(intent);
//            }
//
//            @Override
//            public void onChannelUserLeaved(String account, int uid) {
//                Intent intent = new Intent(Constant.ACTION_ON_CHANNEL_USER_LEAVED);
//                intent.putExtra("account", account);
//                broadcastManager.sendBroadcast(intent);
//            }
//
//            @Override
//            public void onChannelUserList(String[] accounts, int[] uids) {
//                Intent intent = new Intent(Constant.ACTION_ON_CHANNEL_USER_LIST);
//                intent.putExtra("accounts", accounts);
//                broadcastManager.sendBroadcast(intent);
//            }
//
//            @Override
//            public void onMessageSendError(String messageID, int ecode) {
//                Intent intent = new Intent(Constant.ACTION_ON_MESSAGE_SEND_ERROR);
//                intent.putExtra("ecode", ecode);
//                broadcastManager.sendBroadcast(intent);
//            }
//
//            @Override
//            public void onMessageSendSuccess(String messageID) {
//                Intent intent = new Intent(Constant.ACTION_ON_MESSAGE_SEND_SUCCESS);
//                intent.putExtra("messageID", messageID);
//                broadcastManager.sendBroadcast(intent);
//            }
//
//            @Override
//            public void onMessageInstantReceive(String account, int uid, String msg) {
//                Intent intent = new Intent(Constant.ACTION_ON_MESSAGE_INSTANT_RECEIVE);
//                intent.putExtra("account", account).putExtra("msg", msg);
//                broadcastManager.sendBroadcast(intent);
//            }
//
//
//            @Override
//            public void onChannelQueryUserNumResult(String channelID, int ecode, int num) {
//                Intent intent = new Intent(Constant.ACTION_CHANNEL_QUERY_USER_NUM_RESULT);
//                intent.putExtra("channelID", channelID).putExtra("ecode", ecode).putExtra("num", num);
//                broadcastManager.sendBroadcast(intent);
//            }
//
//            @Override
//            public void onLog(String txt) {
//                //Log.d("声网信令安卓端日志：  ",txt);
//            }
//        };
//        MyApplication.getInstance().getmAgoraAPI().callbackSet(agoraCallBack);

    }

    protected void showToast(Context context, final String toastContent) {
        Snackbar.make(((Activity) context).getWindow().getDecorView(), toastContent, Snackbar.LENGTH_LONG).show();

    }

    public String getFilePath() {
        if (TextUtils.isEmpty(filePath)) {
            filePath = getBasePath() + "/file";
        }

        return filePath;
    }

    public String getBasePath() {
        if (TextUtils.isEmpty(basePath)) {
            // basePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + appContext.getPackageName(); 这个路径，在Oppo reno手机上 无法创建文件夹
            basePath = Environment.getExternalStorageDirectory() + "/Android/data/" + appContext.getPackageName();

        }

        return basePath;
    }

    public boolean isNetworkConnected() {
        return networkConnected;
    }

    /**
     * 当账户改变的时候，重登聊天服务器
     */
    public void onAccountChange() {
        //把账户改变的事件 广播出去，各个activity 做清理 重置用户信息等工作
        broadcastManager.sendBroadcast(new Intent(Constant.ACTION_LOGIN_USER_INFO_CHANGE));

//        new Handler(appContext.getMainLooper()).postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                //睡眠1s 后执行 聊天服务器连接
//                try {
//                    Thread.sleep(1000);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//                IMSClientBootstrap.getInstance().login();
//            }
//        }, 1000);

//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                //睡眠1s 后执行 聊天服务器连接
//                try {
//                    Thread.sleep(1000);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//                IMSClientBootstrap.getInstance().login();
////                Helper.getInstance().initStarRtc(UserProfileManager.getInstance().getLoginUserInfo().getuId());
////                Helper.getInstance().starRtcLogin();
//            }
//        }).start();

    }
}
